﻿using System;
using System.Web;
using System.Net.Mail;
using INHollandair.Core.Models;
using INHollandair.Core.Services;

namespace INHollandair.Account
{
    public partial class ChangeUser : System.Web.UI.Page
    {
        private readonly UserService _svc = new UserService();

        protected void Page_Load(object sender, EventArgs e)
        {
            EmailText.Focus();
            pnl_UserEditForm.DefaultButton = "EditUserButton";

            if (Session["UserEditFormSubmitted"] == null)
            {
                pnl_UserEditFormSubmitted.Visible = false;
            }

            if (!IsPostBack)
            {
                LoadUser();
                Session["CaptchaImageText"] = RngUtils.GetRandomNumberAsString(6);
            }
        }

        protected void LoadUser()
        {
            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                //Get user
                User user = _svc.GetUserByName(HttpContext.Current.User.Identity.Name);

                //Set labels
                UserName.Text = user.Name;
                EmailText.Text = user.Email;
            }
            else
            {
                Response.Redirect("~/Account/Login.aspx?ReturnUrl=%2fAccount%2fLogin.aspx");
            }
        }

        protected void EditUserButtonClick(object sender, EventArgs e)
        {
            string captcha = Server.HtmlEncode(txt_Captcha.Text);
            if (captcha.Equals(Session["CaptchaImageText"].ToString()))
            {
                UserService svc = new UserService();

                //Save user
                string username = Server.HtmlEncode(UserName.Text);
                string email = Server.HtmlEncode(EmailText.Text);
                string password = Server.HtmlEncode(Password.Text);

                //Validate input
                if (username.Length > 0 && email.Length > 0 && password.Length > 0)
                {
                    //Get data from database
                    User user = _svc.GetUserByName(HttpContext.Current.User.Identity.Name);

                    bool mailValid = true;
                    MailAddress mail = null;
                    try 
                    {
                        mail = new MailAddress(email);
                    } 
                    catch (FormatException) 
                    {
                        mailValid = false;
                    }

                    if (!mailValid) 
                    {
                        ErrorLabel.Text = "E-mail adres is onjuist.";
                    } 
                    else  
                    {
                        bool mailExists = svc.UserEmailExistsExcludingUser(user, mail.Address);
                        if (!mailExists)
                        {
                            string salt = EncryptionUtils.Salt();
                            string hash = EncryptionUtils.Hash(password, salt);

                            user.Salt = salt;
                            user.Hash = hash;
                            user.Email = mail.Address;

                            svc.UpdateUser(user);

                            Session["UserEditFormSubmitted"] = true;
                            Response.Redirect("~/Account/ChangeUser.aspx");
                        }
                        else
                        {
                            ErrorLabel.Text = "E-mail adres is al bezet.";
                        }
                    }
                }
            }
        }
    }
}